import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;



public class Player extends JFrame implements ActionListener, Runnable  {
        private static final long serialVersionUID = 1L;
       
        private Socket playerSocket;
        private DataOutputStream writer;
        private DataInputStream reader;
       
        JFrame gui;
       
        JPanel mainPanel, buttonsPanel, drawCardsPanel, playerCards, dialogPanel, table,
                        dealerButtonPanel, smallBlindPanel, bigBlindPanel, playAgainPanel;

        JButton button1, button2, button3, button4, button5, button6, button7,
                        connectButton, drawCardsButton, dontDrawCardsButton,
                        checkButton, betButton, raiseButton, callButton, foldButton, allInButton, dialogButton,
                        playAgainButton, exitButton;

        JLabel authors, connectionStatus,
                        hostIPLabel, hostPortLabel, playerNameLabel, dialogInfo,
                        gameNumber, roundNumber,
                        pot, yourBet, maxBet, potLabel, yourBetLabel, maxBetLabel, chipsAmountLabel,
                        card1, card2, card3, card4,
                        checkButtonLabel, betButtonLabel, raiseButtonLabel, callButtonLabel,
                        allInButtonLabel, foldButtonLabel,
                        activityLog, chipsAmount, gameResults,
                        dealerButton, smallBlind, bigBlind,
                        player1 = new JLabel(), player2 = new JLabel(), player3 = new JLabel(),
                        player4 = new JLabel(), player5 = new JLabel(), player6 = new JLabel(),
                        player1bet = new JLabel(), player2bet = new JLabel(), player3bet = new JLabel(),
                        player4bet = new JLabel(), player5bet = new JLabel(), player6bet = new JLabel();
       
        JLabel[] players =
                                new JLabel[]{player1,player2,player3,player4,player5,player6},
                        playersBet =
                                new JLabel[]{player1bet,player2bet,player3bet,player4bet,player5bet,player6bet};

        JCheckBox changeCard1, changeCard2, changeCard3, changeCard4;

        JTextField hostIP, hostPort, playerNameInput, dialogInput;

        Font labelFont = new Font("Helvetica", 1, 11),
                        inputFont = new Font("Ubuntu", 0, 13),
                        cardFont = new Font("Helvetica", 1, 22),
                        logFont = new Font("Ubuntu", 0, 10),
                        buttonFont = new Font("Helvetica", 1, 13),
                        buttonLabelFont = new Font("Helvetica", 0, 9);

        Color inputColor = new Color(0, 180, 255),
                        inputBgColor = new Color(240, 250, 255),
                        black30 = new Color(30, 30, 30),
                        darkBlue = new Color(15, 25, 40),
                        buttonBgColor = darkBlue;
       

       
        String playerName = "Guest";

        private int playerID = 0;
        private int numberOfPlayers = 0;
       
        private int[] coords;
       
        private int[][] allCoords = new int[][]{{73,191,64,76,160,20,297,20,399,76,390,191},
                        {51,147,92,46,228,20,365,41,412,147}};
       
        private String action = "";
       
        private boolean movesEnabled = true,
                        allowPainting = false,
                        connectionOk = false,
                        showHelloPanel = false;

       
        /**
         * Constructor.
         * @param host Server's host.
         * @param port Server's port.
         * @param playerNameTmp Player name set as a parameter.
         */
        public Player(String host, int port, String playerNameTmp, boolean tmpShowHelloPanel) {
                
               
                gui = new JFrame();
                gui.setLayout(null);           
                gui.setTitle("Badugi");
                gui.setResizable(false);
                gui.setDefaultCloseOperation(3);
                gui.setBounds(10, 10, 280, 350);              
               
                /**
                 * Main panel - visible, when player is connected to server.
                 */
                mainPanel = new JPanel();
                mainPanel.setLayout(null);            
                mainPanel.setVisible(false);
                mainPanel.setBounds(0, 0, 750, 510);
                gui.add(mainPanel);
               
               
                /**
                 * A panel with checkboxes and buttons to draw cards.
                 */
                drawCardsPanel = new JPanel();
                drawCardsPanel.setOpaque(false);
                drawCardsPanel.setLayout(null);
                drawCardsPanel.setVisible(false);
                drawCardsPanel.setBounds(34, 395, 460, 90);
                mainPanel.add(drawCardsPanel);
               
                changeCard1 = new JCheckBox();
                changeCard1.setOpaque(false);
                changeCard1.setBounds(0, 45, 30, 20);
                drawCardsPanel.add(changeCard1);

                changeCard2 = new JCheckBox();
                changeCard2.setOpaque(false);
                changeCard2.setBounds(70, 45, 30, 20);
                drawCardsPanel.add(changeCard2);

                changeCard3 = new JCheckBox();
                changeCard3.setOpaque(false);
                changeCard3.setBounds(140, 45, 30, 20);
                drawCardsPanel.add(changeCard3);

                changeCard4 = new JCheckBox();
                changeCard4.setOpaque(false);
                changeCard4.setBounds(210, 45, 30, 20);
                drawCardsPanel.add(changeCard4);

                drawCardsButton = new JButton("<html>Draw cards</html>");
                drawCardsButton.setLayout(null);
                drawCardsButton.setOpaque(true);
                drawCardsButton.setBounds(271, 0, 95, 20);
                drawCardsButton.addActionListener(this);
                drawCardsButton.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white));
                drawCardsPanel.add(drawCardsButton);

                dontDrawCardsButton = new JButton("<html>Don't draw cards</html>");
                dontDrawCardsButton.setLayout(null);
                dontDrawCardsButton.setOpaque(true);
                dontDrawCardsButton.setBounds(271, 25, 125, 20);
                dontDrawCardsButton.addActionListener(this);
                dontDrawCardsButton.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white));
                drawCardsPanel.add(dontDrawCardsButton);

               
                /**
                 * A panel contains player's cards.
                 */
                playerCards = new JPanel();
                playerCards.setOpaque(false);
                playerCards.setLayout(null);
                playerCards.setVisible(false);
                playerCards.setBounds(5, 340, 410, 100);
                mainPanel.add(playerCards);

                card1 = new JLabel();
                card1.setBounds(10, 10, 65, 90);
                card1.setHorizontalAlignment(JLabel.CENTER);
                card1.setFont(cardFont);
                playerCards.add(card1);
               
                card2 = new JLabel();
                card2.setBounds(80, 10, 65, 90);
                card2.setHorizontalAlignment(JLabel.CENTER);
                card2.setFont(cardFont);
                playerCards.add(card2);
               
                card3 = new JLabel();
                card3.setBounds(150, 10, 65, 90);
                card3.setHorizontalAlignment(JLabel.CENTER);
                card3.setFont(cardFont);
                playerCards.add(card3);
               
                card4 = new JLabel();
                card4.setBounds(220, 10, 65, 90);
                card4.setHorizontalAlignment(JLabel.CENTER);
                card4.setFont(cardFont);
                playerCards.add(card4);
               
               
                /**
                 * A panel which displays all info about actions.
                 */
                dialogPanel = new JPanel();
                dialogPanel.setOpaque(false);
                dialogPanel.setLayout(null);
                dialogPanel.setBounds(15, 315, 480, 20);
                mainPanel.add(dialogPanel);

                dialogInput = new JTextField();
                dialogInput.setOpaque(true);
                dialogInput.setLayout(null);
                dialogInput.setBounds(382, 0, 40, 20);
                dialogInput.setVisible(false);
                dialogInput.setHorizontalAlignment(JTextField.CENTER);
                dialogInput.setBorder(null);
                dialogPanel.add(dialogInput);

                dialogInfo = new JLabel();
                dialogInfo.setBounds(0, 0, 380, 20);
                dialogInfo.setText("Waiting for more players.");
                dialogPanel.add(dialogInfo);
               
                dialogButton = new JButton();
                dialogButton.setOpaque(true);
                dialogButton.setLayout(null);
                dialogButton.setBounds(425, 0, 35, 20);
                dialogButton.setText("OK");
                dialogButton.addActionListener(this);
                dialogButton.setVisible(false);
                dialogButton.setVerticalAlignment(JButton.CENTER);
                dialogButton.setBorder(null);
                dialogPanel.add(dialogButton);

               
                /**
                 * Table panel.
                 */            
                table = new JPanel();
                table.setLayout(null);
                table.setOpaque(true);
                table.setBounds(0, 0, 500, 300);
                mainPanel.add(table);
               
                gameNumber = new JLabel();
                gameNumber.setBounds(3,3,100,13);;
                table.add(gameNumber);
               
                roundNumber = new JLabel();
                roundNumber.setBounds(3,15,100,12);
                table.add(roundNumber);

                potLabel = new JLabel("Pot:");
                potLabel.setOpaque(true);
                potLabel.setLayout(null);
                potLabel.setBounds(0, 264, 125, 16);
                potLabel.setVerticalAlignment(JLabel.BOTTOM);               
                potLabel.setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, darkBlue));
                table.add(potLabel);

                pot = new JLabel("$0");
                pot.setOpaque(true);
                pot.setLayout(null);
                pot.setBounds(0, 280, 125, 20);
                pot.setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, darkBlue));
                pot.setVerticalAlignment(JLabel.TOP);
                table.add(pot);

                chipsAmountLabel = new JLabel("Your chips:");
                chipsAmountLabel.setOpaque(true);
                chipsAmountLabel.setLayout(null);
                chipsAmountLabel.setBounds(125, 264, 125, 16);
                chipsAmountLabel.setVerticalAlignment(JLabel.BOTTOM);
                table.add(chipsAmountLabel);
               
                chipsAmount = new JLabel("$0");
                chipsAmount.setOpaque(true);
                chipsAmount.setLayout(null);
                chipsAmount.setBounds(125, 280, 125, 20);
                chipsAmount.setVerticalAlignment(JLabel.TOP);
                table.add(chipsAmount);

                yourBetLabel = new JLabel("Your total bet:");
                yourBetLabel.setOpaque(true);
                yourBetLabel.setLayout(null);
                yourBetLabel.setBounds(250, 264, 125, 16);
                yourBetLabel.setVerticalAlignment(JLabel.BOTTOM);                
                table.add(yourBetLabel);

                yourBet = new JLabel("$0");
                yourBet.setOpaque(true);
                yourBet.setLayout(null);
                yourBet.setBounds(250, 280, 125, 20);
                yourBet.setVerticalAlignment(JLabel.TOP);;
                table.add(yourBet);

                maxBetLabel = new JLabel("Call (max bet):");
                maxBetLabel.setOpaque(true);
                maxBetLabel.setLayout(null);
                maxBetLabel.setBounds(375, 264, 125, 16);
                maxBetLabel.setVerticalAlignment(JLabel.BOTTOM);
                table.add(maxBetLabel);

                maxBet = new JLabel("$0");
                maxBet.setOpaque(true);
                maxBet.setLayout(null);
                maxBet.setBounds(375, 280, 125, 20);
                maxBet.setVerticalAlignment(JLabel.TOP);;
                table.add(maxBet);
               
               
                /**
                 * Display a 'dealer button' next to its holder.
                 */
                dealerButtonPanel = new JPanel() {
                        public void paintComponent(Graphics g) {
                                super.paintComponent(g);
                                        g.setColor(Color.pink);
                                        g.fillOval(0,0,14,14);                              
                       }
                };
                dealerButtonPanel.setVisible(false);
                dealerButtonPanel.setOpaque(false);
                dealerButtonPanel.setLayout(null);
                dealerButtonPanel.setBorder(null);
                dealerButtonPanel.setBounds(0, 0, 14, 14);
                table.add(dealerButtonPanel);
               
               
                /**
                 * Displays a 'small blind' next to its holder.
                 */
                smallBlindPanel = new JPanel() {
                        public void paintComponent(Graphics g) {
                                super.paintComponent(g);                                
                                g.setColor(new Color(175,210,230));
                                g.fillOval(0,0,14,14);                               
                        }
                };
                smallBlindPanel.setVisible(false);
                smallBlindPanel.setOpaque(false);
                smallBlindPanel.setLayout(null);
                smallBlindPanel.setBorder(null);
                smallBlindPanel.setBounds(0, 0, 14, 14);
                table.add(smallBlindPanel);
               
               
                /**
                 * Displays a 'big blind' next to its holder.
                 */
                bigBlindPanel = new JPanel(){
                    public void paintComponent(Graphics g) {
                               super.paintComponent(g);                                             
                        	   g.setColor(Color.green);
                               g.fillOval(0,0,14,14);                        
                       }
                };
                bigBlindPanel.setVisible(false);
                bigBlindPanel.setOpaque(false);
                bigBlindPanel.setLayout(null);
                bigBlindPanel.setBorder(null);
                bigBlindPanel.setBounds(0, 0, 14, 14);
                table.add(bigBlindPanel);
               
               
                /**
                 * Panel contains all action buttons:
                 * check, bet, call, raise, all-in, fold.
                 */
                buttonsPanel = new JPanel();
                buttonsPanel.setOpaque(false);
                buttonsPanel.setLayout(null);
                buttonsPanel.setVisible(false);
                buttonsPanel.setBounds(320, 350, 155, 210);
                mainPanel.add(buttonsPanel);

                checkButton = new JButton("Check");
                checkButton.addActionListener(this);
                checkButton.setBounds(0, 0, 70, 20);
                checkButton.setOpaque(true);
                buttonsPanel.add(checkButton);

                betButton = new JButton("Bet");
                betButton.addActionListener(this);
                betButton.setBounds(0, 35, 70, 20);
                betButton.setOpaque(true);
                buttonsPanel.add(betButton);

                callButton = new JButton("Call");
                callButton.addActionListener(this);
                callButton.setBounds(0, 70, 70, 20);
                callButton.setOpaque(true);
                buttonsPanel.add(callButton);

                raiseButton = new JButton("Raise");
                raiseButton.addActionListener(this);
                raiseButton.setBounds(85, 0, 70, 20);
                raiseButton.setOpaque(true);
                buttonsPanel.add(raiseButton);

                allInButton = new JButton("All-in");
                allInButton.addActionListener(this);
                allInButton.setBounds(85, 35, 70, 20);
                allInButton.setOpaque(true);
                buttonsPanel.add(allInButton);

                foldButton = new JButton("Fold");
                foldButton.addActionListener(this);
                foldButton.setBounds(85, 70, 70, 20);
                foldButton.setOpaque(true);               
                buttonsPanel.add(foldButton);
               
               
                /**
                 * Play again panel.
                 */
                playAgainPanel = new JPanel();
                playAgainPanel.setOpaque(false);
                playAgainPanel.setLayout(null);
                playAgainPanel.setVisible(false);
                playAgainPanel.setBounds(320, 350, 155, 210);
                mainPanel.add(playAgainPanel);

                playAgainButton = new JButton("Play again");
                playAgainButton.addActionListener(this);
                playAgainButton.setBounds(0, 0, 90, 20);
                playAgainButton.setOpaque(true);
                playAgainPanel.add(playAgainButton);

                exitButton = new JButton("Exit");
                exitButton.addActionListener(this);
                exitButton.setBounds(0, 25, 90, 20);
                exitButton.setOpaque(true);
                playAgainPanel.add(exitButton);

               
                /**
                 * A JLabel contains game history.
                 */
                activityLog = new JLabel();
                activityLog.setOpaque(true);
                activityLog.setBounds(500, 0, 250, 500);
                activityLog.setVerticalAlignment(JLabel.TOP);
                mainPanel.add(activityLog);
               
               
                /**
                 * A JLabel contains all cards when game is over.
                 */
                gameResults = new JLabel();
                gameResults.setOpaque(false);
                gameResults.setVisible(false);
                gameResults.setBounds(20,300,300,188);
                gameResults.setBorder(BorderFactory.createMatteBorder(0,20,0,0,new Color(0,0,0,0)));
                mainPanel.add(gameResults);               
               

                 playerName = playerNameTmp;
                 connectToServer(host, port);
        }

       
        /**
         * Connects and checks if connection was successful.
         * @param host Server's IP address.
         * @param port Server's port.
         */
        private void connectToServer(String host, int port) {
                try {                       
                       
                        playerSocket = new Socket(host, port);

                        reader = new DataInputStream(playerSocket.getInputStream());
                        writer = new DataOutputStream(playerSocket.getOutputStream());

                        Thread th = new Thread(this);
                        th.start();

                        sendRequest("setPlayerName " + playerName);
                       
                        try {
                                Thread.sleep(500);
                        } catch (Exception e) {}
                        {
                                System.out.println(" > Successfully connected to server :)");
                               
                              
                                gui.setVisible(true);
                                gui.setSize(750, 510);                                
                                mainPanel.setVisible(true);
                        }
                       
                } catch (IOException e) {
                        System.out.println(" > Cannot connect to '" + host + "' (port: " + port + ")");
                        System.exit(-1);
                }
        }
       
       
        /**
         * Sends a single request to server.
         * @param message Request to send.
         */
        private void sendRequest(String message) {
                try {
                        writer.writeUTF(message);
                } catch (IOException e) {
                        System.out.println(e);
                }
        }
       
       
        /**
         * Listens and proceeds all responses from server.
         */
        public void run() {
               
                try {
                        while (true) {
                                String response = reader.readUTF();
                               
                                if (response == null) {
                                        continue;
                                }
                                       
                                String[] tab = response.split(" ");
                                String cmd = tab[0];


                                if (cmd.equalsIgnoreCase("numberOfPlayers")) {
                                        connectionOk = true;
                                        numberOfPlayers = Integer.parseInt(tab[1]);
                                        setCoords(numberOfPlayers);
                                       
                                        allowPainting = true;
                                       
                                        table.repaint();
                                        drawTableComponents();
                                       
                                } else if (cmd.equalsIgnoreCase("yourID")) {
                                        playerID = Integer.parseInt(tab[1]);
                                       
                                } else if (cmd.equalsIgnoreCase("yourName")) {
                                       
                                        playerName = tab[1];
                                        players[playerID-1].setText(playerName);
                                       
                                } else if (cmd.equalsIgnoreCase("yourCards")) {
                                       
                                        JLabel[] cardLabel = new JLabel[] { card1, card2, card3, card4 };

                                        for (int i = 0; i < cardLabel.length; i++) {
                                                String[] card = convertCardToShape(tab[(i + 1)]);

                                                if (card[1].equalsIgnoreCase("Red")) {
                                                        cardLabel[i].setForeground(Color.RED);
                                                } else {
                                                        cardLabel[i].setForeground(Color.BLACK);
                                                }

                                                cardLabel[i].setText("<html>" + card[0] + "</html>");
                                        }
                                       
                                } else if (cmd.equalsIgnoreCase("yourChips")) {
                                        chipsAmount.setText("$" + tab[1]);
                                       
                                } else if (cmd.equalsIgnoreCase("gameIsReady")) {
                                        sendRequest("returnMyCards");
                                        sendRequest("returnMyChips");
                                       
                                } else if (cmd.equalsIgnoreCase("actionOk")) {
                                       
                                        if (action.equalsIgnoreCase("fold")) {
                                                mainPanel.remove(buttonsPanel);
                                                mainPanel.remove(playerCards);
                                                dialogInfo.setText("You left the game :(");
                                               
                                                System.exit(0);
                                        }
                                       
                                        action = "";
                                       
                                } else if (cmd.equalsIgnoreCase("actionError")) {
                                       
                                        buttonsPanel.setVisible(true);

                                        if (action.equals("allIn")) {
                                                action = "All-in";
                                        } else {
                                                action = action.substring(0, 1).toUpperCase() + action.substring(1);
                                        }

                                        dialogInfo.setText(" you can't play" + action + "because you have not enough chips.");
                                        dialogInfo.setVisible(true);
                                        action = "";
                                       
                                } else if (cmd.equalsIgnoreCase("drawCardsSuccess")) {
                                       
                                        drawCardsPanel.setVisible(false);
                                        dialogInfo.setText("Waiting for other players.");
                                        dialogInfo.setVisible(true);
                                       
                                } else if (cmd.equalsIgnoreCase("dontDrawCardsSuccess")) {
                                       
                                        drawCardsPanel.setVisible(false);
                                        dialogInfo.setText("Waiting for other players.");
                                        dialogInfo.setVisible(true);

                                } else if (cmd.equalsIgnoreCase("nextPlayerMove")) {
                                       
                                        if ((tab[1].equalsIgnoreCase(playerID + "")) && (movesEnabled)) {
                                                addActivityEvent("Your move.");

                                                if (checkButton.isEnabled() != Boolean.parseBoolean(tab[3]))
                                                        checkButton.setEnabled(Boolean.parseBoolean(tab[3]));

                                                if (betButton.isEnabled() != Boolean.parseBoolean(tab[4]))
                                                        betButton.setEnabled(Boolean.parseBoolean(tab[4]));

                                                if (callButton.isEnabled() != Boolean.parseBoolean(tab[5]))
                                                        callButton.setEnabled(Boolean.parseBoolean(tab[5]));

                                                if (raiseButton.isEnabled() != Boolean.parseBoolean(tab[6]))
                                                        raiseButton.setEnabled(Boolean.parseBoolean(tab[6]));

                                                if (allInButton.isEnabled() != Boolean.parseBoolean(tab[7]))
                                                        allInButton.setEnabled(Boolean.parseBoolean(tab[7]));

                                                buttonsPanel.setVisible(true);
                                        } else {
                                                addActivityEvent("<span style=\"color:#666666\">&nbsp; Next move: <b>" + tab[2] + "</b>.</span>");

                                                if (buttonsPanel.isVisible() == true)
                                                        buttonsPanel.setVisible(false);

                                        }
                                       
                                } else if (cmd.equalsIgnoreCase("startOfTheGame")) {

                                        addActivityEvent("START OF THE GAME!");
                                       
                                        sendRequest("returnMyChips");
                                        playerCards.setVisible(true);
                                        dialogInfo.setText("");
                                        gameNumber.setText("Game #" + tab[1]);
                                       
                                } else if (cmd.equalsIgnoreCase("newRound")) {
                                       
                                        dialogInfo.setText("");
                                        roundNumber.setText("Round " + tab[1]);

                                        if (tab[1].equals("1")) {
                                                addActivityEvent("NEW ROUND - bet (1/7)");
                                               
                                                if (tab[2].equalsIgnoreCase(playerID + "")) {
                                                        addActivityEvent("First move is yours.");

                                                        if (checkButton.isEnabled() != Boolean.parseBoolean(tab[9]))
                                                                checkButton.setEnabled(Boolean.parseBoolean(tab[9]));

                                                        if (betButton.isEnabled() != Boolean.parseBoolean(tab[10]))
                                                                betButton.setEnabled(Boolean.parseBoolean(tab[10]));

                                                        if (callButton.isEnabled() != Boolean.parseBoolean(tab[11]))
                                                                callButton.setEnabled(Boolean.parseBoolean(tab[11]));

                                                        if (raiseButton.isEnabled() != Boolean.parseBoolean(tab[12]))
                                                                raiseButton.setEnabled(Boolean.parseBoolean(tab[12]));

                                                        if (allInButton.isEnabled() != Boolean.parseBoolean(tab[13]))
                                                                allInButton.setEnabled(Boolean.parseBoolean(tab[13]));

                                                        buttonsPanel.setVisible(true);
                                                } else {
                                                        addActivityEvent("First move:" + tab[3]);
                                                }
                                                       
                                                if (tab[5].equals(playerID + ""))
                                                        yourBet.setText("$" + tab[6]);
                                                else if (tab[7].equals(playerID + ""))
                                                        yourBet.setText("$" + tab[8]);

                                               
                                                redrawBlinds(Integer.parseInt(tab[4]), Integer.parseInt(tab[5]), Integer.parseInt(tab[7]));
                                               
                                                playersBet[Integer.parseInt(tab[5])-1].setText("$" + tab[6]);
                                                playersBet[Integer.parseInt(tab[7])-1].setText("$" + tab[8]);
                                               
                                                dealerButtonPanel.setVisible(true);
                                                smallBlindPanel.setVisible(true);
                                                bigBlindPanel.setVisible(true);
                                               
                                        } else if (Integer.parseInt(tab[1]) % 2 == 0) {
                                                addActivityEvent("NEW ROUND - draw your cards (" + tab[1]);

                                                if (movesEnabled) {
                                                        drawCardsPanel.setVisible(true);
                                                }
                                        } else {
                                                addActivityEvent("NEW ROUND - bet (" + tab[1]);
                                               
                                                maxBet.setText("$0");
                                               
                                                for (int i = 0; i < numberOfPlayers; i++)
                                                        if (!playersBet[i].getText().contains("All-in") && !playersBet[i].getText().contains("Fold"))
                                                                playersBet[i].setText("");
                                        }
                                       
                                } else if (cmd.equalsIgnoreCase("endOfRound")) {
                                       
                                        addActivityEvent(" End of round.");
                                       
                                        if (Integer.parseInt(tab[1]) % 2 != 0)
                                                buttonsPanel.setVisible(false);
                                       
                                } else if (cmd.equalsIgnoreCase("endOfGame")) {
                                        addActivityEvent("END OF THE GAME!");
                                       
                                       
                                        yourBet.setText("$0");
                                        maxBet.setText("$0");
                                        pot.setText("$0");
                                        dialogInfo.setText("");
                                        gameNumber.setText("");
                                        roundNumber.setText("");
                                        drawCardsPanel.setVisible(false);
                                       
                                        if (buttonsPanel.isVisible()) {
                                                buttonsPanel.setVisible(false);
                                        }
                                       
                                       
                                        if (tab[1].equalsIgnoreCase("winner")) {
                                                if (tab[2].equals(playerID + "")) {
                                                        chipsAmount.setText("$" + tab[4]);
                                                        addActivityEvent("You won the game");
                                                } else {
                                                        addActivityEvent("Winner: " + tab[3]);
                                                }
                                               
                                        } else {
                                                addActivityEvent("It's a tie");
                                        }
                                       
                                        for (int i = 0; i < numberOfPlayers; i++) {
                                                playersBet[i].setText("");
                                        }
                                       
                                        dealerButtonPanel.setVisible(false);
                                        smallBlindPanel.setVisible(false);
                                        bigBlindPanel.setVisible(false);
                                       
                                        addActivityEvent("");
                                       
                                } else if (cmd.equalsIgnoreCase("playersCanPlayAgain")) {
                                        boolean canIPlay = false;
                                       
                                        for (int i = 1; i < tab.length; i++) {
                                                if (tab[i].equals(playerID + "")) {
                                                        canIPlay = true;
                                                        break;
                                                }
                                        }
                                       
                                       
                                        if (canIPlay) {
                                                if (!playAgainButton.isVisible()) {
                                                        playAgainButton.setVisible(true);
                                                }
                                                       
                                                playAgainPanel.setVisible(true);
                                               
                                        } else {
                                               
                                                try {
                                                        Thread.sleep(5000);
                                                } catch (Exception e) {}
                                               
                                               
                                                gui.remove(mainPanel);
                                                gui.setSize(500, 60);
                                               
                                                JLabel tmp = new JLabel();
                                                tmp.setOpaque(true);
                                                tmp.setBounds(0,0,500,38);
                                                tmp.setText("You can't play again, because you have not enough chips. Sorry :(");
                                                tmp.setVerticalAlignment(JLabel.CENTER);
                                                tmp.setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, new Color(0,0,0,0)));
                                                gui.add(tmp);
                                               
                                                sendRequest("nextGameNo");
                                                return;
                                        }
                                       
                                       
       
                                } else if (cmd.equalsIgnoreCase("disableMoves")) {
                                       
                                        movesEnabled = false;
                                       
                                } else if (cmd.equalsIgnoreCase("scaleDownGui")) {
                                       
                                        gui.setSize(750, 322);
                                       
                                } else if (cmd.equalsIgnoreCase("tableUpdate")) {

                                        if (tab[1].equals("potAndMaxBet")) {
                                                pot.setText("$" + tab[2]);
                                                maxBet.setText("$" + tab[3]);
                                               
                                        } else if (tab[1].equals("yourBet")) {
                                                yourBet.setText("$" + tab[2]);
                                               
                                        } else if (tab[1].equals("newPlayer")) {
                                                players[Integer.parseInt(tab[2])-1].setText(tab[3]);

                                        } else if (tab[1].equals("allCurrentPlayers")) {
                                                for (int i = 2; i+1 < tab.length; i+=2) {
                                                        players[Integer.parseInt(tab[i])-1].setText(tab[i+1]);
                                                }
                                               
                                        } else if (tab[1].equals("playerBet")) {
                                                playersBet[Integer.parseInt(tab[2])-1].setText("$" + tab[3]);
                                       
                                        } else if (tab[1].equals("allIn")) {
                                                playersBet[Integer.parseInt(tab[2])-1].setText("All-in");
                                       
                                        } else if (tab[1].equals("fold")) {
                                                players[Integer.parseInt(tab[2])-1].setText("");
                                                playersBet[Integer.parseInt(tab[2])-1].setText("red");
                                       
                                        } else if (tab[1].equals("dealerAndBlinds")) {
                                                redrawBlinds(Integer.parseInt(tab[2]), Integer.parseInt(tab[3]), Integer.parseInt(tab[4]));
                                       
                                        } else if (tab[1].equals("showCards")) {
                                                String str = "";
                                               
                                                if (playerCards.isVisible())
                                                        playerCards.setVisible(false);
                                               
                                                for (int i = 2; i+4 < tab.length; i+=5) {      
                                                       
                                                        if (tab[i] == null || tab[i].equals("null"))
                                                                continue;
                                                       
                                                        str += "<div style=\"padding-bottom:3px\">";
                                                        str += "<div style=\"font-size:7px\">"+tab[i]+"</div>";
                                                       
                                                        for (int j = 1; j <= 4; j++) {
                                                                String[] card = convertCardToShape(tab[i+j]);
                                                               
                                                                if (card[1].equalsIgnoreCase("black"))
                                                                        card[1] = "white";
                                                               
                                                                str += "&nbsp; <b><span style=\"color:" + card[1] + "\">" + card[0] + "</span></b>";
                                                        }
                                                       
                                                        str += "</div>";
                                                }
                                               
                                                gameResults.setVisible(true);
                                                gameResults.setText("<html>" + str + "</html>");
                                               
                                        } else if (tab[1].equals("playerGaveUpGame")) {
                                                players[Integer.parseInt(tab[2])-1].setText("");
                                                addActivityEvent("Player "+tab[3]+"gave up the game");
                                        }
                                       
                                } else {
                                        addActivityEvent(response);
                                }

                        }
                } catch (IOException e) { }
        }

       
        /**
         * Add new activity event to game history in GUI.
         * @param event
         */
        private void addActivityEvent(String event) {
                String str = activityLog.getText();

                if (str.length() > 13) {
                        str = str.substring(6, str.length() - 7);
                }
               
                str = "<div style=\"padding: 2px 3px; width:494px; border-bottom:1px dashed #233750;\">" + event + "</div>" + str;
                activityLog.setText("<html>" + str + "</html>");
        }

       
        /**
         * Convert String(13-Red-Diamond) to VAl-HTML_SHAPE to display it in GUI.
         * @param card
         * @return
         */
        private String[] convertCardToShape(String card) {
                String[] cards = card.split("-");
                String shape = ""; 

                try {
                        if (cards[2].equals("Spade"))
                                shape = "&spades;";
                        else if (cards[2].equals("Club"))
                                shape = "&clubs;";
                        else if (cards[2].equals("Diamond"))
                                shape = "&diams;";
                        else
                                shape = "&hearts;";
               
                        switch (Integer.parseInt(cards[0])) {
                                case 1: {
                                        cards[0] = "A"; break; }
                                case 11: {
                                        cards[0] = "J"; break; }
                                case 12: {
                                        cards[0] = "Q"; break; }
                                case 13: {
                                        cards[0] = "K"; break; }
                        }
                       
                } catch (Exception e) {
                       
                }

                return new String[] {cards[0] + shape, cards[1]};
        }
               
       
        /**
         * Set coordinates needed to draw table components.
         * @param numOfPlyrs Number of players.
         */
        private void setCoords(int numOfPlyrs) {
                coords = new int[2*numOfPlyrs];
                int index = 0;
               
                for (int i = (6-numOfPlyrs%2)-numOfPlyrs; i <= numOfPlyrs+(5-numOfPlyrs%2); i++) {
                        coords[index] = allCoords[numOfPlyrs%2][i];
                                               
                        index += 1;
                }
        }
       
       
        /**
         * Reposition all components related with players.
         */
        private void drawTableComponents() {
                for (int i = 0; i < numberOfPlayers; i++) {
                        players[i] = new JLabel();
                        players[i].setBounds(coords[2*i]-24, coords[2*i+1]+34, 80, 14);
                        players[i].setHorizontalAlignment(JLabel.CENTER);
                        players[i].setVerticalAlignment(JLabel.CENTER);
                        table.add(players[i]);
                       
                        playersBet[i] = new JLabel();
                        playersBet[i].setBounds(coords[2*i]-24, coords[2*i+1]+48, 80, 14);
                        playersBet[i].setHorizontalAlignment(JLabel.CENTER);
                        playersBet[i].setVerticalAlignment(JLabel.CENTER);
                        table.add(playersBet[i]);
                }
        }
       
       
        /**
         * Change position of small, big blind and dealer button on table.
         * @param dealer ID of player who owns dealer button.
         * @param small ID of player who owns small blind.
         * @param big ID of player who owns big blind.
         */
        private void redrawBlinds(int dealer, int small, int big) {
                dealer -= 1;
                small -= 1;
                big -= 1;
               
                dealerButtonPanel.setBounds(coords[2 * dealer] + 58, coords[2 * dealer + 1] + 35, 14, 14);
                smallBlindPanel.setBounds(coords[2*small] + 58, coords[2 * small + 1] + 50, 14, 14);
                bigBlindPanel.setBounds(coords[2 * big] + 58, coords[2 * big + 1] + 50, 14, 14);
        }
       
       
        /**
         * @param str Input string.
         * @param color Color (for ex.: orange, yellow or #000000).
         * @return A string with HTML brackets (span) with in-line style.
         */

       
       
        public void actionPerformed(ActionEvent evt) {
                if (evt.getSource() == dialogButton) {
                       
                        if ((action != "") || (action != null)) {
                                dialogInfo.setText(null);
                                dialogButton.setVisible(false);
                                dialogInput.setVisible(false);
                               
                                if ((action.equalsIgnoreCase("bet")) || (action.equalsIgnoreCase("raise"))) {
                                        try {
                                                int amount = Integer.parseInt(dialogInput.getText());
                                               
                                                if (amount <= 0)
                                                        dialogInfo.setText("Error: minimum value is $1.");
                                                else
                                                        sendRequest(action + " " + dialogInput.getText());
                                               
                                        } catch (Exception e) {
                                                dialogInfo.setText("Error: value must be an integer.");
                                        }
                                       
                                        dialogInput.setText("");
                                } else
                                        sendRequest(action);
                        }
                } else if (evt.getSource() == checkButton) {
                        action = "check";

                        if (dialogButton.isVisible() != true)
                                dialogButton.setVisible(true);
                       
                        if (dialogInput.isVisible() == true)
                                dialogInput.setVisible(false);
                       
                        dialogInfo.setText("<html>Are you sure, you want to play <b>Check</b>?</html>");

                } else if (evt.getSource() == betButton) {
                       
                        action = "bet";
                       
                        if (dialogButton.isVisible() != true)
                                dialogButton.setVisible(true);

                        if (dialogInput.isVisible() != true)
                                dialogInput.setVisible(true);
                       
                        dialogInfo.setText("<html>First bet amount:</html>");
                       
                } else if (evt.getSource() == raiseButton) {
                       
                        action = "raise";

                        if (dialogButton.isVisible() != true)
                                dialogButton.setVisible(true);

                        if (dialogInput.isVisible() != true)
                                dialogInput.setVisible(true);

                        dialogInfo.setText("<html>How much do you want to <b>raise</b>?</html>");
                       
                } else if (evt.getSource() == callButton) {
                       
                        action = "call";

                        if (dialogButton.isVisible() != true)
                                dialogButton.setVisible(true);

                        if (dialogInput.isVisible() == true) {
                                dialogInput.setVisible(false);
                        }

                        dialogInfo.setText("<html>Are you sure, you want to play <b>call</b>?</html>");
                       
                } else if (evt.getSource() == allInButton) {
                       
                        action = "allIn";

                        if (dialogButton.isVisible() != true)
                                dialogButton.setVisible(true);
                       
                        if (dialogInput.isVisible() == true)
                                dialogInput.setVisible(false);

                        dialogInfo.setText("<html>Are you sure, you want to play <b>all-in</b>?</html>");
                       
                } else if (evt.getSource() == foldButton) {
                       
                        action = "fold";

                        if (dialogButton.isVisible() != true)
                                dialogButton.setVisible(true);

                        if (dialogInput.isVisible() == true)
                                dialogInput.setVisible(false);

                        dialogInfo.setText("<html>Are you sure, you want to leave the game? :(</html>");
                       
                } else if (evt.getSource() == drawCardsButton) {
                       
                        String cardsToChange = "";
                       
                        if (changeCard1.isSelected())
                                cardsToChange += " 1";
                       
                        if (changeCard2.isSelected())
                                cardsToChange += " 2";

                        if (changeCard3.isSelected())
                                cardsToChange += " 3";

                        if (changeCard4.isSelected())
                                cardsToChange += " 4";

                        if (cardsToChange != "")
                                sendRequest("drawMyCards" + cardsToChange);

                        changeCard1.setSelected(false);
                        changeCard2.setSelected(false);
                        changeCard3.setSelected(false);
                        changeCard4.setSelected(false);
                       
                } else if (evt.getSource() == dontDrawCardsButton) {
                       
                        sendRequest("dontDrawMyCards");
                        drawCardsPanel.setVisible(false);
                       
                } else if (evt.getSource() == connectButton) {
                       
                        String host = hostIP.getText();
                        int port;

                        try {
                                port = Integer.parseInt(hostPort.getText());
                        } catch (Exception e) {
                                port = 4444;
                        }

                        playerName = playerNameInput.getText();
                       
                        connectToServer(host, port);
                       
                } else if (evt.getSource() == playAgainButton) {
                        sendRequest("nextGameYes");
                       
                        playAgainPanel.setVisible(false);
                        gameResults.setVisible(false);                       
                       
                } else if (evt.getSource() == exitButton) {
                       
                        sendRequest("nextGameNo");
                        System.exit(0);
                       
                } else {
                        sendRequest(evt.getActionCommand());
                }
        }
       
       
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
       
       
        public void mouseClicked(MouseEvent e) {}
       
       
        public void mouseEntered(MouseEvent e) {}

       
        public void mouseExited(MouseEvent e) {}

       
        /**
         * Main
         * @param args
         */
        public static void main(String[] args) {
                String playerName = null;
                boolean defaultSettings = true;
                int port;          
                String host;

                try {
                	    playerName = args[2];
                        host = args[0];
                        port = Integer.parseInt(args[1]);
                } catch (Exception e) {
                	    playerName = "guest";
                        port = 4442;
                        host = "localhost";
                }
            
            
                new Player(host, port, playerName, defaultSettings);
        }
}